<template>
  <div v-if="orderShowing">

    <!-- 中间导航 breadcrumb-->
    <el-breadcrumb class="breadcrumb-container" separator="/">
      <el-breadcrumb-item :to="{ path: '/admin/restaurant' }">admin</el-breadcrumb-item>
      <el-breadcrumb-item>order</el-breadcrumb-item>
    </el-breadcrumb>

    <el-main v-loading='isLoading'>
      <!-- 时间选择 -->
      <div class="block">
        <el-date-picker v-model="value2" type="daterange" align="right"
          unlink-panels range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" :picker-options="pickerOptions" @change="sendTime"
          >
        </el-date-picker>
      </div>

      <!-- 为 ECharts 准备一个具备大小（宽高）的 DOM -->
    <div class="chart-style">
      <v-chart class="chart1" :option="optionFirst" />
      <v-chart class="chart2" :option="optionSecond" />
    </div>
    <div class="chart-box">
      <v-chart class="chart3" :option="optionThird" />
    </div>
    </el-main>

  </div>
</template>

<script>
import { get } from '@/common/utils';
import moment from 'moment';
import _ from 'lodash';
import { mapState, mapActions } from 'vuex';
import { qc, getAllDate } from '@/views/admin/components/Order/OrderFunction';

export default {
  data() {
    return {
      aaa: '',
      value2: [],
      pickerOptions: { // 最近一周 最近一个月 最近三个月
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          },
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          },
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          },
        }],
      },
      optionFirst: { // 第一个折线图
        xAxis: {
          type: 'category',
          data: [],
        },
        yAxis: {
          type: 'value',
        },
        series: [{
          itemStyle: {
            normal: {
              color: '#c94b48', // 折点自定义颜色
              lineStyle: {
                color: '#c94b48', // 线条自定义颜色
              },
            },
          },
          data: [],
          type: 'line',
        }],
      },
      optionSecond: { // 第2个饼状图
        tooltip: {
          trigger: 'item',
        },
        series: [
          {
            name: '下单日期',
            type: 'pie',
            radius: '50%',
            label: {
              normal: {
                show: true,
                formatter: '{b}: {c}({d}%)', // 自定义显示格式(b:name, c:value, d:百分比)
              },
            },
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      },
      optionThird: {
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        series: [
          {
            name: '面积模式',
            type: 'pie',
            radius: [50, 250],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 8,
            },
            data: [],
          },
        ],
      },
    };
  },

  computed: {
    ...mapState({
      orderStatisData: (state) => state.order.orderStatisData,
      isLoading: (state) => state.loading.isShow,
      orderShowing: (state) => state.login.orderShow,
    }),

    orderStatisState() {
      return this.orderStatisData;
    },

    orderShowing() {
      return get('orderShowStore');
    },

  },

  watch: {
    orderStatisState(val) {
      if (val) {
        this.optionFirstData();
      }
    },
  },

  methods: {
    ...mapActions([
      'getOrderStatis',
    ]),
    // 发送请求，选中的时间
    sendTime() {
      const start = this.value2[0].toISOString(); // toISOString 国际标准时间
      const end = this.value2[1].toISOString();
      this.getOrderStatis({ start, end });
    },

    // //* optionFirstData函数是将后端返回的时间、下单次数、转化成moment对象，整理好使用
    optionFirstData() {
      const createdAtArray = [];

      _.forEach(this.orderStatisData, (element) => {
        const createdAtTime = _.get(element, 'createdAt');
        createdAtArray.push(moment(createdAtTime).format('YYYY-MM-DD'));
      });

      //* 筛选出 count和date 相对应，存放到对象数组当中
      // 使用getAllDate，将选中的时间moment格式化之后，才能传参到 getAllDate 函数当中
      const AllDate = getAllDate(moment(this.value2[0]).format('YYYY-MM-DD'),
        moment(this.value2[1]).format('YYYY-MM-DD'));
      const caculateNum = qc(createdAtArray);
      let usefulDataArry = [];
      const usefulDataObj = { date: '', count: '' };
      _.forEach(AllDate, (item) => {
        _.forEach(caculateNum, (element) => {
          if (item === element.name) { // 如果存在日期相等的话就，就改变count，否则count: 0
            usefulDataObj.date = element.name;
            usefulDataObj.count = element.num;
            usefulDataArry.push({ date: usefulDataObj.date, count: usefulDataObj.count });
          }
        });
        usefulDataArry.push({ date: item, count: 0 });
      });

      //* 百度→ 数组对象去重
      // array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
      // (function(必选初始值或计算结束返回值, 必选当前元素, 可选索引, 可选原数组),可选函数初始值)
      const obj = {};
      function dateCount() {
        usefulDataArry = usefulDataArry.reduce((a, b) => {
          // eslint-disable-next-line no-unused-expressions
          obj[b.date] ? '' : obj[b.date] = true && a.push(b);
          return a;
        }, []);
        return usefulDataArry;
      }
      const dateCountArray = dateCount();

      //* 将结合在一起的date count 的对象数组，拆成单个的date数组和count数组
      const xAxisData = [];
      const seriesData = [];
      _.forEach(dateCountArray, (item) => {
        xAxisData.push(item.date);
        seriesData.push(item.count);
      });
      this.$data.optionFirst.xAxis.data = xAxisData;
      this.$data.optionFirst.series[0].data = seriesData;
      // console.log('xAxisData==>', xAxisData);

      //! 第2个饼状图的函数
      //* js修改对象的key值
      const result = dateCountArray.map((item) => ({ value: item.count, name: item.date }));
      this.$data.optionSecond.series[0].data = result;

      //! 第3个饼状图
      const nameCartArray = [];
      _.forEach(this.orderStatisData, (item) => {
        nameCartArray.push({ name: item.user.username, cartNum: item.cart.length });
      });
      const objThird = _.groupBy(nameCartArray, 'name');

      //* 拿出name 和点单个数
      const usefulThirdData = [];
      _.forEach(objThird, (v, key) => {
        usefulThirdData.push({ value: v.length, name: key }); // 取得value  objThird[key]
      });

      this.$data.optionThird.series[0].data = usefulThirdData;
    },
  },

};
</script>

<style lang="scss" scoped>
/deep/ .el-main{
  text-align : left;
}

.chart-style{
  display : flex;
  width : 100%;
  height : 450px;
}

.chart-box{
  width : 100%;
  height : 600px;
  margin-top : 10px;
}
</style>
